package com.yanqu.road.server.cmd.activity.douluodalu;

import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuConfig;
import com.yanqu.road.pb.activity.douluodalu.DouLuoDaLuProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.douluodalu.DouLuoDaLuMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

@Cmd(code = Protocol.S_DOU_LUO_DA_LU_OPEN_BOX,desc = "打开宝箱")
public class DouLuoDaLuOpenBoxCmd extends AbstractCommand {


    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        if ((ret = DouLuoDaLuMgr.canEntryActivity(player)) != 0) return;


        DouLuoDaLuConfig config = DouLuoDaLuMgr.getConfig();

        DouLuoDaLuProto.DouLuoDaLuOpenBoxReqMsg reqMsg = DouLuoDaLuProto.DouLuoDaLuOpenBoxReqMsg.parseFrom(packet.getBytes());

        //宝箱id校验
        if(!config.getBoxOpenConsume().containsKey(reqMsg.getBoxId())){
            ret = GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            return;
        }

        if(reqMsg.getNum() <= 0){
            ret = GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            return;
        }

        String consume = config.getBoxOpenConsume().get(reqMsg.getBoxId());
        Property consumeProperty = PropertyHelper.parseStringToProperty(consume);
        if(reqMsg.getNum() > 1){
            consumeProperty.rideProperty(reqMsg.getNum());
        }
        if(!player.getModule(CurrencyModule.class).currencyIsEnough(consumeProperty)){
            ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            return;
        }
        player.getModule(PreReduceModule.class).preReduce(consumeProperty);

        DouLuoDaLuProto.DouLuoDaLuOpenBoxCrossReqMsg.Builder crossReq = DouLuoDaLuProto.DouLuoDaLuOpenBoxCrossReqMsg.newBuilder();
        crossReq.setActivityId(DouLuoDaLuMgr.getActivityInfo().getActivityId());
        crossReq.setBoxId(reqMsg.getBoxId());
        crossReq.setNum(reqMsg.getNum());
        player.sendUnionActivityGroupPacket(Protocol.C_DOU_LUO_DA_LU_OPEN_BOX, crossReq, crossReq.getActivityId());


    }

    @Override
    public void sendData(GamePlayer player) {
        if(ret != 0){
            player.sendPacket(Protocol.U_DOU_LUO_DA_LU_OPEN_BOX, DouLuoDaLuProto.DouLuoDaLuOpenBoxRespMsg.newBuilder().setRet(ret));
        }
    }
}
